const getCategorytitle = () =>
  ajax({
    url: "http://chst.vip:1234/api/getcategorytitle",
  });

getCategorytitle().then((res) => {
  let lisArr = res.result;
  // console.log(res);
  let nameLis = document.querySelector(".nameLis");

  //创建每一个大LI
  let lisHtml = "";
  lisArr.forEach((item) => {
    lisHtml += `
    <li>
    <div>
        <div>${item.title}</div>
        <span class="iconfont icon-xiangxia"></span>
    </div>
    </li>
    `;
  });
  nameLis.innerHTML = lisHtml;

  let lis_ul = document.querySelector(".nameLis");
  let lis_li = lis_ul.children;

  //添加每一个小li，并添加点击功能
  for (let i = 0; i < lis_li.length; i++) {
    lis_li[i].index = i;
    // 点击事件注册到上面的dv上，以免干扰二级菜单跳转
    let lis_li_dv = lis_li[i].firstElementChild 
    lis_li_dv.onclick = function () {
      let bigLi = lis_li[i];
      // 排他，每次点击把已有的删除，同时如果点的是自己就不创建
      let flag = true;
      for (let j = 0; j < lis_li.length; j++) {
        if (lis_li[j].children.length == 2) {         
          let ul = lis_li[j].children[1];
          lis_li[j].removeChild(ul);       
          if(j == lis_li[i].index){           
            flag = false;
          }
        }
      }
      //如果都没有ul就按照点击的li创建
      if (flag) {
        const getCategoryLis = () =>
          ajax({
            url: "http://chst.vip:1234/api/getcategory",
            data: { titleid: i },
          });

        getCategoryLis().then((res) => {
          let lisArr2 = res.result;
          let ul = document.createElement("ul");

          lisArr2.forEach((item) => {
            let li = document.createElement("li");
            li.innerText = item.category;
            ul.appendChild(li);
            bigLi.appendChild(ul);
            //二级菜单点击跳转其他页面
            li.onclick = function(){
              localStorage.setItem('categoryId',item.categoryId)
              location.href = './bijia.html'
            }
          });         
        });
      }
    };
  }
});

// 点击回到顶部
let backTop = document.querySelector(".footer-main>div>a");
backTop.onclick = function (e) {
  e.preventDefault();
  let distans = document.documentElement.scrollTop;
  let distansControl = setInterval(function () {
    distans -= 10;
    document.documentElement.scrollTop = distans;
    if (distans <= 0) {
      clearInterval(distansControl);
    }
  }, 3);
};